<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\api\model\GoodsModel;
use app\api\model\GoodCate;
use app\api\model\GoodSpace;
use think\exception\ValidateException;
use think\Request;
use think\Response;
use think\facade\Validate;
use app\api\validate\Goods as GoodsValidate;


class Goods extends Base
{
    /**
     * 显示资源列表
     *
     * @return Response
     */
    public function index(): Response
    {
        //withJoin选择字段的用法
        //dump($this->title);
        if(empty($this->user_id)){
            return $this->create([], '用户参数错误', 0);
        }
        $data =  GoodsModel::with(['space','cate'])->field('id,title,stock,logo,space_id,cate_id,end_time')
            ->where('user_id','=',$this->user_id)
            ->whereLike('title','%' . $this->title . '%')
            ->page($this->page, $this->pageSize)
            ->select();
        if($data->isEmpty()) {
            return $this->create([], '无数据', 0);
        } else {
            return $this->create($data, '数据获取成功',1);
        }
    }

    /**
     * 返回物品分类列表
     *
     * @param Request $request
     * @return Response
     */
    public  function getCateList(): Response
    {
        $data = GoodCate::field('id,title')->select();
        return $this->create($data, '物品分类获取成功',1);
    }

    /**
     * 保存新建的资源
     *
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        //
        $data = $request->param();
        //验证返回
        try {
            Validate(GoodsValidate::class)->check($data);
        }catch (ValidateException $exception) {
            return $this->create([], $exception->getError(), 400);
        }
        $data['end_time'] = strtotime($data['end_time']);
        $id = GoodsModel::create($data)->getData('id');
        if(Empty($id)) {
            return $this->create([], '数据保存失败', 0);
        } else {
            return $this->create($id, '数据保存成功',1);
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return Response
     */
    public function read($id): Response
    {
        if(!Validate::isInteger($id)) {
            return $this->create([], 'id参数不合法', 400);
        }
        //删除数据
        $data = GoodsModel::with(['space','cate'])
                            ->field('id,title,stock,logo,space_id,cate_id,end_time,remark')
                            ->find($id);
        //find()返回为 array 或者 null
        //dump($data);
        if(Empty($data)) {
            return $this->create([], '无数据', 0);
        } else {
            return $this->create($data, '数据获取成功',1);
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param int $id
     * @return Response
     */
    public function update(Request $request, int $id): Response
    {
        //
        if(!Validate::isInteger($id)) {
            return $this->create([], 'id参数不合法', 400);
        }
        return $this->create([], 'update', 204);
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return Response
     */
    public function delete($id): Response
    {
        if(!Validate::isInteger($id)) {
            return $this->create([], 'id参数不合法', 400);
        }
        //删除数据
        try {
            GoodsModel::find($id)->delete();
            return $this->create([], '数据删除成功', 200);
        } catch (\Error $e) {
            return $this->create([], '数据删除错误', 400);
        }

    }

    public function getSpaceList(): Response
    {
        $list        = GoodSpace::field('id,pid,title')
            ->where([
                ['status', '=', 1],
            ])
            ->select()
            ->toArray();
        $arrs = [];
        //$cateNodes = json_encode($this->recur($arrs,$list));
        $cateNodes = $this->recur($arrs,$list);
        return $this->create($cateNodes, '空间读取成功', 1);
    }

    private function recur($arrs,$category,$parent_id = 0)
    {
        foreach ($category as $k => $v) {
            if($v['pid'] == $parent_id)
            {
                $arr = array('id'=>$v['id'],'title'=>$v['title'],'children'=>array());
                $arr['children'] = $this->recur($arr['children'],$category,$v['id']);
                array_push($arrs,$arr);
            }
        }
        return $arrs;
    }

    function getSpaceKv($id) : Response
    {
        $data = $this->getParent($id);
        $data = array_reverse($data);
        //array_reverse($data);
        if(Empty($data)) {
            return $this->create([], '无空间数据', 204);
        } else {
            return $this->create($data, '数据获取成功',1);
        }
    }
    private function getParent( $pid ,$array=[]) {
        static $level = 1;
        $is_parent = GoodSpace::field("id,pid,title")->where(["id"=>$pid])->find();
        if(empty($is_parent)) return $array;
        $array[] = $is_parent;
        if ( $is_parent["pid"] ) {
            $level++;
            return $this->getParent( $is_parent['pid'],$array);
        }
        return $array;
    }
}

